package exam.wzb.jsp.dao.impl;

import com.mysql.jdbc.Connection;
import exam.wzb.jsp.dao.AccountDao;
import exam.wzb.jsp.model.Account;
import exam.wzb.jsp.utils.DruidUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccountDaoImpl implements AccountDao {

    @Override
    public void addAccount(Account account) {

    }

    @Override
    public Account findAccountById(int aid) {
        return null;
    }

    @Override
    public void updateAccount(Account account) {

    }

    @Override
    public List<Account> findAllAccounts() {
        return null;
    }

    @Override
    public void transfer(int fromAccountId, int toAccountId1, int toAccountId2, double amount) throws SQLException {
        Connection conn = null;
        try {
            conn = (Connection) DruidUtil.getDataSource().getConnection(); // 从Druid数据源获取连接
            conn.setAutoCommit(false); // 开始事务

            // 从fromAccount扣钱
            updateBalance(conn, fromAccountId, -amount);
            // 给toAccount1和toAccount2各加钱（一半）
            updateBalance(conn, toAccountId1, amount / 2);
            updateBalance(conn, toAccountId2, amount / 2);

            conn.commit(); // 提交事务
        } catch (SQLException e) {
            if (conn != null) {
                conn.rollback(); // 回滚事务
            }
            throw e; // 重新抛出异常供上层处理
        } finally {
            if (conn != null) {
                conn.close(); // 关闭连接（实际上由Druid管理）
            }
        }
    }

    private void updateBalance(Connection conn, int accountId, double amount) throws SQLException {
        // SQL语句，更新账户余额
        String sql = "UPDATE account SET abalance = abalance + ? WHERE aid = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setDouble(1, amount);
        pstmt.setInt(2, accountId);
        pstmt.executeUpdate();
    }
    // 这里使用Map来模拟数据库
    private Map<Integer, Account> database = new HashMap<>();

    @Override
    public Account findAccountById(int id) {
        return database.get(id);
    }

    @Override
    public void updateAccountBalance(Account account) {
        database.put(account.getAid(), account);
    }



}
